package com.yjf.ljr.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Bitmap.CompressFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.yjf.ljr.R;
import com.yjf.ljr.adapter.ShareSDKAdapter;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.onekeyshare.CustomerLogo;
import com.yjf.ljr.onekeyshare.OnekeyShare;
import com.yjf.ljr.onekeyshare.OnekeyShareTheme;
import com.yjf.ljr.util.MediaScanner;
import com.yjf.ljr.util.ShareCustomerDialog;
import com.yjf.ljr.view.Untilly;

public class QrCodeActivity extends IjActivity implements OnClickListener {

	@ID("ivQrCode")
	private ImageView mIvQrCode; //

	@ID("tvQeCodeNo")
	private TextView mTvQeCodeNo; //
	// 图片宽度的一般
	private static final int IMAGE_HALFWIDTH = 50;
	// 前景色
	int FOREGROUND_COLOR = 0xff000000;
	// 背景色
	int BACKGROUND_COLOR = 0xffffffff;
	private Bitmap mIcon;
	private String mQrcodeUrl;

	private ShareSDKAdapter mShareSDKAdapter;
	private ArrayList<Object> mShareSDKItems;
	private String mImagepath = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_qrcode);
		initControls();

		new Thread() {
			public void run() {
				initImagePath();
			}
		}.start();
	}

	/** 初始化控件 **/
	private void initControls() {
		setLeftBtnClick();
		setTitleStr("推广二维码");
		mIvQrCode.setOnClickListener(this);
		mIcon = BitmapFactory.decodeResource(getResources(), R.drawable.icon_lld);
		mQrcodeUrl = getIntent().getStringExtra("QrCodeUrl");
		if (!TextUtils.isEmpty(mQrcodeUrl)) {

			/*
			 * http://192.168.45.92:28150/app/preRegist.htm?referees=yxK00527
			 */
			String[] arrayReferees = mQrcodeUrl.split("referees=");
			if (arrayReferees.length > 1) {
				if (!TextUtils.isEmpty(arrayReferees[1])) {
					mTvQeCodeNo.setText("你的二维码编号：" + arrayReferees[1]);
				} else {
					mTvQeCodeNo.setText("你的二维码编号：");
				}
			} else {
				mTvQeCodeNo.setText("你的二维码编号：");
			}
			try {
				Bitmap bitmap = cretaeBitmap(new String(mQrcodeUrl.getBytes(), "UTF-8"), mIcon);

				mIvQrCode.setImageBitmap(bitmap);
			} catch (UnsupportedEncodingException e) {

				Toast.makeText(this, "出错！", 3000).show();
			} catch (WriterException e) {

				Toast.makeText(this, "出错！", 3000).show();
			}
		}

		/***/
		// try {
		// Bitmap bm = GetQrCodeBitmap(qrcodeUrl, BarcodeFormat.QR_CODE);
		// mIvQrCode.setImageBitmap(bm);
		// } catch (WriterException e) {
		// e.printStackTrace();
		// }

		ShareSDK.initSDK(this);
		mShareSDKItems = new ArrayList<Object>();
		mShareSDKAdapter = new ShareSDKAdapter(this, mShareSDKItems);
		getShareSDKItems();

		TextView tvRight = (TextView) findViewById(R.id.tv_title_right);
		tvRight.setVisibility(View.GONE);
		tvRight.setText("分享");
		tvRight.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showShareSDK();
			}
		});
	}

	public Bitmap GetQrCodeBitmap(String string, BarcodeFormat format) throws WriterException {
		MultiFormatWriter writer = new MultiFormatWriter();
		Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();
		hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix matrix = writer.encode(string, format, 300, 300, hst);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					pixels[y * width + x] = 0xff000000;
				}
			}
		}
		Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap,具体参考api
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}

	/**
	 * 生成二维码 中间插入小图片
	 * 
	 * @param str
	 *            内容
	 * @return Bitmap
	 * @throws WriterException
	 */
	public Bitmap cretaeBitmap(String str, Bitmap icon) throws WriterException {
		// 缩放一个40*40的图片
		icon = Untilly.zoomBitmap(icon, IMAGE_HALFWIDTH);
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, 1);
		// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
		BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 650, 650, hints);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		// 二维矩阵转为一维像素数组,也就是一直横着排了
		int halfW = width / 2;
		int halfH = height / 2;
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH && y > halfH - IMAGE_HALFWIDTH
						&& y < halfH + IMAGE_HALFWIDTH) {
					pixels[y * width + x] = icon.getPixel(x - halfW + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
				} else {
					if (matrix.get(x, y)) {
						pixels[y * width + x] = FOREGROUND_COLOR;
					} else { // 无信息设置像素点为白色
						pixels[y * width + x] = BACKGROUND_COLOR;
					}
				}

			}
		}
		Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

		return bitmap;
	}

	private void getShareSDKItems() {
		new AsyncTask<Void, Void, Platform[]>() {

			@Override
			protected Platform[] doInBackground(Void... params) {
				return ShareSDK.getPlatformList();
			}

			@Override
			protected void onPostExecute(Platform[] platforms) {
				mShareSDKItems.clear();
				if (platforms != null && platforms.length > 0) {
					mShareSDKItems.addAll(Arrays.asList(platforms));
				}
				getCustomerItems();
				if (mShareSDKAdapter != null)
					mShareSDKAdapter.notifyDataSetChanged();
			}
		}.execute();
	}

	private void showShareSDK() {
		final ShareCustomerDialog dialog = new ShareCustomerDialog(this);

		GridView gridView = dialog.getGridView();
		gridView.setAdapter(mShareSDKAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				dialog.dismiss();

				Object item = mShareSDKAdapter.getItem(arg2);
				if (item instanceof Platform) {
					showShare(((Platform) item).getName());
				} else {
					CustomerLogo customerLogo = (CustomerLogo) item;
					customerLogo.listener.onClick(arg0.getChildAt(arg2));
				}
			}

		});
		dialog.show();
	}

	private void getCustomerItems() {
		CustomerLogo itemCopy = new CustomerLogo();
		itemCopy.enableLogo = BitmapFactory.decodeResource(getResources(), R.drawable.logo_copy);
		itemCopy.label = "复制链接";
		mShareSDKItems.add(itemCopy);
		itemCopy.listener = new View.OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
				clipboard.setText(mQrcodeUrl);
				showToast("数据已复制");
			}
		};
	}

	private void showShare(String platform) {
		OnekeyShare oks = new OnekeyShare();
		if (!TextUtils.isEmpty(platform) && (platform.equals("QQ"))) {
			oks.setTitle("关注乐乐贷（www.lele365.com）300元体验金等着你！");
		} else if (!TextUtils.isEmpty(platform) && (platform.equals("Wechat"))) {
			oks.setText("关注乐乐贷（www.lele365.com）300元体验金等着你！");
		} else if (!TextUtils.isEmpty(platform) && (platform.equals("WechatMoments"))) {
			oks.setTitle("乐乐贷（www.lele365.com）本息安全的互联网投融资平台，预期年化收益率9%—14%，项目由专业机构提供担保，通过手机快速完成注册还送300元体验金！"
					+ mQrcodeUrl);
		} else {
			oks.setTitle("乐乐贷（www.lele365.com）本息安全的互联网投融资平台，预期年化收益率9%—14%，项目由专业机构提供担保，通过手机快速完成注册还送300元体验金！"
					+ mQrcodeUrl);
			oks.setText("乐乐贷（www.lele365.com）本息安全的互联网投融资平台，预期年化收益率9%—14%，项目由专业机构提供担保，通过手机快速完成注册还送300元体验金！" + mQrcodeUrl);
		}

		oks.setTitleUrl(mQrcodeUrl);
		oks.setImagePath(mImagepath);
		// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/05/21/oESpJ78_533x800.jpg");

		oks.setUrl(mQrcodeUrl);
		// oks.setFilePath(CustomShareFieldsPage.getString("filePath",
		// MainActivity.TEST_IMAGE));
		// oks.setComment("comment");
		// oks.setSite(CustomShareFieldsPage.getString("site",
		// context.getString(R.string.app_name)));
		// oks.setSiteUrl(CustomShareFieldsPage.getString("siteUrl",
		// "http://mob.com"));
		oks.setVenueName("乐乐贷");
		oks.setVenueDescription("乐乐贷");
		oks.setSilent(false);
		oks.setShareFromQQAuthSupport(false);
		oks.setTheme(OnekeyShareTheme.CLASSIC);

		if (platform != null) {
			oks.setPlatform(platform);
		}

		// 令编辑页面显示为Dialog模式
		oks.setDialogMode();

		// 在自动授权时可以禁用SSO方式
		// if(!CustomShareFieldsPage.getBoolean("enableSSO", true))
		oks.disableSSOWhenAuthorize();

		// 去除注释，则快捷分享的操作结果将通过OneKeyShareCallback回调
		// oks.setCallback(new OneKeyShareCallback());

		// 去自定义不同平台的字段内容
		// oks.setShareContentCustomizeCallback(new
		// ShareContentCustomizeDemo());

		// 去除注释，演示在九宫格设置自定义的图标
		// Bitmap enableLogo = BitmapFactory.decodeResource(getResources(),
		// R.drawable.ic_launcher);
		// Bitmap disableLogo = BitmapFactory.decodeResource(getResources(),
		// R.drawable.logo_bluetooth);
		// String label = getResources().getString(R.string.app_name);
		// OnClickListener listener = new OnClickListener() {
		// public void onClick(View v) {
		// String text = "Customer Logo -- ShareSDK " +
		// ShareSDK.getSDKVersionName();
		// Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
		// }
		// };
		// oks.setCustomerLogo(enableLogo, disableLogo, label, listener);

		// 去除注释，则快捷分享九宫格中将隐藏新浪微博和腾讯微博
		// oks.addHiddenPlatform(SinaWeibo.NAME);
		// oks.addHiddenPlatform(TencentWeibo.NAME);

		// 为EditPage设置一个背景的View
		// oks.setEditPageBackground(getPage());
		// 启动分享GUI
		oks.show(this);
	}

	private void initImagePath() {
		try {
			mImagepath = CommonData.IMAMGE_DIR_SD + "share_pic.jpg";
			File file = new File(mImagepath);
			if (!file.exists()) {
				file.createNewFile();
				Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.icon_lld);
				FileOutputStream fos = new FileOutputStream(file);
				pic.compress(CompressFormat.JPEG, 100, fos);
				fos.flush();
				fos.close();
			}
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	private Bitmap createBitmap(View v) {
		Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		v.draw(canvas);
		return bitmap;
	}

	private void saveBitmap(Bitmap bitmap) {
		try {
			if (!TextUtils.isEmpty(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", ""))) {
				// 扫描一个文件
				MediaScanner mediaScanner = new MediaScanner(QrCodeActivity.this);
				String fileMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
				String[] filePaths = new String[] { Environment.getExternalStorageDirectory().getAbsolutePath() + "" };
				String[] mimeTypes = new String[] { fileMimeType };
				mediaScanner.scanFiles(filePaths, mimeTypes);
				showToast("已经保存到系统相册");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			showToast("保存失败");
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ivQrCode:
			AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext);
			mBuilder.setTitle("提示");
			mBuilder.setMessage("是否保存图片到相册");
			mBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					Bitmap mBitmap = createBitmap(mIvQrCode);
					saveBitmap(mBitmap);
				}
			});
			mBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

				}
			});
			mBuilder.create().show();
			break;

		default:
			break;
		}

	}
}
